import express, {
    Express,
    Request,
    Response,
    NextFunction,
    ErrorRequestHandler,
} from "express";
import cors from "cors";
import path from "path";
import proxyRouter from "./router/proxy";
import mcpRouter from "./router/mcp";
import { ROOT_DIR } from "./util/path_util";
import { initMcpClient } from "./mcp/client";

const app: Express = express();
const PORT: number = parseInt(process.env.PORT || "3001", 10);

(async function () {
    await initMcpClient();
    // 启用 CORS
    app.use(cors());

    // 提供静态文件服务
    const staticFileDir = path.join(ROOT_DIR, "client/dist");
    console.log("staticFileDir", staticFileDir);
    app.use(express.static(staticFileDir));

    interface MCPErrorResponse {
        error: string;
        message: string;
    }
    app.use("/mcp", mcpRouter);
    app.use("/proxy", proxyRouter);

    // 错误处理中间件
    const errorHandler: ErrorRequestHandler = (
        err: Error,
        req: Request,
        res: Response<MCPErrorResponse>,
        next: NextFunction,
    ) => {
        console.error("Server error:", err);
        res.status(500).json({
            error: "Internal server error",
            message: err.message,
        });
    };
    app.use(errorHandler);

    // 处理未找到的路由
    app.use((req: Request, res: Response<MCPErrorResponse>) => {
        res.status(404).json({
            error: "Not found",
            message: "The requested resource was not found",
        });
    });

    // 启动服务器
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
})();
